from rest_framework.generics import ListAPIView
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from goods.models import SKU, GoodsCategory, SKUSpecification
from meiduo_admin.goods.sku_serializers import SKUSerializer
from meiduo_admin.my_paginations import MyPageNumberPagination
from meiduo_admin.goods.sku_serializers import GoodsCategorySerializer


class SKUViewSet(ModelViewSet):
    serializer_class = SKUSerializer
    pagination_class = MyPageNumberPagination

    def get_queryset(self):
        keyword = self.request.query_params.get('keyword')
        keyword = keyword if keyword else ''
        return SKU.objects.filter(name__contains=keyword)

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        specs = request.data.get('specs')
        for spec in specs:
            SKUSpecification.objects.create(spec_id=spec['spec_id'], option_id=spec['option_id'], sku_id=serializer.data['id'])
        return Response(serializer.data, status=201)


class SKUCategoriesView(ListAPIView):
    queryset = GoodsCategory.objects.filter(subs=None)
    serializer_class = GoodsCategorySerializer
